<script setup lang="ts">
import { ref, onMounted, onBeforeMount, nextTick, watch } from 'vue';
import { defineProps } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import CommentUnit from '../../components/post/CommentUnit.vue'
import PostCard from '../../components/post/PostCard.vue'
import router from '@/router';
import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { useAccountStore } from '@/stores/account';
import { deletePostApi,likeApi,sendCommentApi,getCommentsApi,sendPostApi,type PostApi, getPostApi } from '@/api/path/post';
import { obsClient } from '@/utils/obs';
const route = useRoute();

const props = defineProps({
  post: Object,
  showCommentBox: Boolean
});

const emit = defineEmits([
  'updateList'
])

// 当前用户
const user = useAccountStore().user;

// 是否点赞
const isLike = ref(false);

// 删除弹窗可视
const deleteVisible = ref(false);

// 评论文本 
const commentText = ref('');

// 是否展示评论
const showCommentBox = ref(false);

// 展示评论数量
const showCommentCount = ref('3');

let avatar_id = -1;

const sharePost = ref({})

const comments = ref([])

// 判断route是否有postid
const isPostIdPresent = computed(() => route.query.postId !== undefined);
// 判断该动态是否是当前用户发的
const isEdit = ref(computed(()=>props?.post?.userId === useAccountStore().user.id));

const avatar = ref();


// 该程序依靠下面这个bug运行
// 二编：该程序不依靠这个bug运行
const setSharePost = async () => {
  // sharePost.value = await getSharePost(props?.post?.shareId);
  try {
    await nextTick();
    if (props?.post?.isShared) {
      sharePost.value = await getSharePost(props?.post?.shareId);
    }
  } catch (error) {
    // console.error("Error sharing post:", error);
  }
};

watch(props, (newValue, oldValue) => {
      isEdit.value = !isEdit.value;
      setSharePost();
});
onBeforeMount(()=>{
  setSharePost();
})
onMounted(() => {
  comments.value = props?.post?.comments;
  if (showCommentBox.value) {
    showCommentBox.value = !showCommentBox.value;
  }

  if (isPostIdPresent.value) {
    showCommentBox.value = !showCommentBox.value;
    getComments(String(route.query.postId));
  }
  if(props.post.userId){
    requestAvatar(props.post.userId)
  }else if(route.query.userId){
    requestAvatar(route.query.userId)
  }
  
});

const getSharePost = async (shareId: string) =>{
  try {
    const res = await getPostApi(shareId);
    if (res.errno === 1) {
      return res.post;
    } else {
      ElMessage.error(res.msg);
      return null;
    }
  } catch (error) {
    ElMessage.error('获取动态失败');
    return null;
  }
}
// 点赞
const like = (postid:string) => {
  likeApi(postid).then(res => {
    if (res.success) {
      props.post.likesCount++;
    }
    else {
      ElMessage.error(res.msg);
    }
  })
}

// 展示评论盒子（完成）
const showBox = () => {
  showCommentBox.value = !showCommentBox.value;
}

// 提交发布(待测试)
const submitPost = (content:string) => {
  if (!content.trim()) {
    ElMessage.error('发布内容不能为空！');
    return;
  }
  const param : PostApi = {
        content: content,
        imageKey: [],
        isShared: true,
        shareId: props?.post?.postId,
  }
  sendPostApi(param).then(res => {
    if (res.success) {
      emit('updateList', true);
      ElMessage.success(res.msg)
    }
    else {
      ElMessage.error(res.msg);
    }
  })

}

// 分享动态
const share = () => {
    ElMessageBox.prompt('写下你想说的吧', '转发', {
    confirmButtonText: '转发',
    cancelButtonText: '取消',
    inputErrorMessage: '请输入',
  })
  .then(({ value }) => {
    if (value) {
        submitPost(value);
        props.post.sharesCount++;

    } else {
      ElMessage({
        type: 'warning',
        message: '发布内容不能为空，请写下你想说的吧'
      });
    }
  })
}

// 获取评论列表
const getComments = (postId: string, count?: string) => {
  if(count){
    getCommentsApi(postId, count).then(res => {
      if (res.success) {
        comments.value = res.comments;
        // console.log("[comments]:",comments.value)
        // ElMessage.success(res.msg)
      }
      else {
        ElMessage.error(res.msg);
      }
    })
  }else{
    getCommentsApi(postId).then(res => {
      if (res.success) {
        comments.value = res.comments;
        // console.log(comments.value)
        // ElMessage.success(res.msg)
      }
      else {
        ElMessage.error(res.msg);
      }
    })
  }
}

// 发表评论
const submitComment = () => {
  props.post.commentsCount++;
  if (commentText.value.trim()) {
    const postid = ref(props?.post?.postId)
    // 提交评论逻辑
    sendCommentApi(postid.value,commentText.value).then(res => {
      if (res.success) {
        if(route.query.postId){
          getComments(props?.post?.postId);
        }else {
          getComments(props?.post?.postId,showCommentCount.value);
        }
        ElMessage.success(res.msg)
      }
      else {
        ElMessage.error(res.msg);
      }
    })
    commentText.value = '';
  } else {
    // 提示评论内容不能为空
  }
}

// 去动态(完成)
const toThisPost = () => {
    router.push({
      path: "/post",
      query: {
        userId: props?.post?.userId,
        postId: props?.post?.postId,
      }
    });
}

// 删除动态
const deleteThis = (postid:string) => {
  deleteVisible.value = !deleteVisible.value;
  deletePostApi(postid).then(res => {
    if (res.errno === 1) {
      // console.log("删除咯")
      emit('updateList', true);
      ElMessage.success(res.msg);
    }
    else {
      ElMessage.error(res.msg);
    }
  })
}
const toThisUser = () => {
    router.push({
    path: "/personalinfo",
      query: {
        userId: props?.post?.userId,
      }
    });
}

// 获取头像
const isHadAva = ref(false);
const requestAvatar = (id) => {
  const obs = obsClient; 
    obs.listObjects({
      Bucket: 'job-linker',
      Prefix: "personal/avatar/" + id + '/',
    }).then(result => {
      console.log("requestAvatar");
      console.log(result);
      if (result.CommonMsg.Status < 300 && result.InterfaceResult.Contents && result.InterfaceResult.Contents.length > 0) {
        let contents = result.InterfaceResult.Contents
        let element = contents[0]
        let index = 0
        for (index = contents.length - 1; index >= 0; index--) {
          element = contents[index]
          if (element.Key.endsWith('.jpeg') && element.Key.startsWith('personal/avatar/' + id + '/')) {
            break
          }
        }
        if (index<0) {
          return
        }
        avatar_id = index + 1
        let path = element.Key
        console.log("avatar_id",path)
        return obsClient.getObject({
          Bucket: 'job-linker',
          Key: path,
          SaveByType: 'arraybuffer',
        }).then(result => {
          if (result.CommonMsg.Status < 300) {
            const arrayBuffer = result.InterfaceResult.Content;
            const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });
            const url = URL.createObjectURL(blob);
            avatar.value = url; // 更新响应式引用
            isHadAva.value = true;
            console.log("=================================",avatar.value)
          } 
        });
      }
    }).catch(error => {
      console.error('请求头像列表时发生错误：', error);
      ElMessage({
      message: '请求头像列表失败。',
      type: 'error',
    });
  });
};
</script>

<template>
  <div class="post-unit">
    <!-- 动态信息-->
    <div class="header">
      <span class="header-left">
        <el-avatar 
        v-if="isHadAva"
        class="avatar" 
        :src="avatar" 
        @click="toThisUser"></el-avatar> 
        <el-avatar v-else class="avatar" @click="toThisUser"> {{ String($props.post.username).charAt(0) }}</el-avatar>
        <span class="user-info">
          <h3>{{ props?.post?.username }}</h3>
          <span class="time">{{ props?.post?.time }}</span>
        </span>
      </span>
      <span v-show="isEdit">
        <el-dropdown >
        <el-button>
          <el-icon><More /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="deleteVisible = true">删除</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      </span>
    </div>

    <!-- 删除弹窗 -->
    <el-dialog
      v-model="deleteVisible"
      width="500"
    >
      <span>确定要删除这条动态吗？</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteThis(props?.post?.postId)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 动态内容 -->
    <div class="content">
      <!-- 文图 -->
      <PostCard :post="$props.post" ></PostCard>
      <!-- 转发 -->
      <el-card class="shared-card" v-if="props?.post?.isShared" >
        <PostCard :post="sharePost"></PostCard>
      </el-card>
    </div>

    <!-- 动态互动 -->
    <div class="actions">
      <div class="action" @click="like(props?.post?.postId)">
        <el-icon v-show="!isLike"><Star /></el-icon>
        <el-icon v-show="isLike"><StarFilled /></el-icon>
        <span>{{ props?.post?.likesCount }}</span>
      </div>
      <div class="action" @click="showBox">
        <el-icon v-show="!showCommentBox"><ChatDotSquare /></el-icon>
        <el-icon v-show="showCommentBox"><Comment /></el-icon>
        <span>{{ props?.post?.commentsCount }}</span>
      </div>
      <div class="action" @click="share">
        <el-icon><Share /></el-icon>
        <span>{{ props?.post?.sharesCount }}</span>
      </div>
    </div>
    <el-divider v-if="showCommentBox" />

    <!-- 发表评论 -->
    <div>
      <div class="comments" v-if="showCommentBox">
        <!-- 评论输入框 -->
        <textarea
          v-model="commentText"
          placeholder="写下你的评论..."
          class="comment-textarea"
          @keyup.enter="submitComment"
          :row="4"
        />
        <!-- 发表评论按钮 -->
        <el-button type="primary" @click="submitComment" class="sendBtn">发布</el-button>
      </div>


      <!--评论列表 只显示最新3条评论,查看详情后进入动态详情，使用无限滚条或者分页查看所有-->
      <div class="comments-list" v-if="showCommentBox"> <!-- 调试记得改成isHadPosts -->
          <el-scrollbar>
            <p v-for="comment in comments" :key="comment.cid" >
              <CommentUnit :comment="comment" :request-avatar="requestAvatar"></CommentUnit>
            </p>
          </el-scrollbar>
          <div class="bottom-bar">
            <span>共<span>{{ props?.post?.commentsCount }}</span>条评论</span>
            <span @click="toThisPost" v-if="!isPostIdPresent">查看详情<el-icon><ArrowRight /></el-icon></span>
          </div>
      </div>
    </div>
  </div>
  
</template>

<style scoped>
.post-unit {
  margin-bottom: 5px;
  position: relative;
  padding: 20px;
  background-color: white;
  border-radius: 15px;
  border: 2px solid var(--color-plain);
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header-left {
  display: flex;
  align-items: center;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 24px;
}

.user-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-left: 12px;
  text-align: left; 
}

.content {
  margin: 12px 0; 
}
.content-text {
  margin-left: 2.5px;
}

.actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 8px;
}

.action {
  cursor: pointer;
  margin-right: 16px;
}

.action span {
  margin-left: 4px;
}

.comments {
  display: flex;
  align-items: center;
  margin-top: 12px;
}

.comment-textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: none;
  min-height: 60px;
  font-family: 'Helvetica Neue';
}
.sendBtn {
  min-height: 60px;
  margin-left: 5px;
}

.bottom-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: default;
}
.shared-card {
  box-shadow: none;
}

</style>